package com.zhengjiang.log4j2.demo;

import com.zhengjiang.code.utils.PropertiesUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @ClassName Log4j2DemoApplication
 * @Description
 * @Author zhengjiang(99514925 @ qq.com)
 * @Date 2020-06-24 13:28
 * @Version V1.0
 **/
@SpringBootApplication
@ServletComponentScan(basePackages = {"com.zhengjiang.log4j2.demo.filter"})
@Slf4j
public class Log4j2DemoApplication {

    public static void main(String[] args) {
        initMainThreadLogProperties();
        SpringApplication.run(Log4j2DemoApplication.class,args);
    }

    private static void initMainThreadLogProperties(){
        try {
            PropertiesUtil propertiesUtil = new PropertiesUtil("application.properties");
            MDC.put("ip",getLocalIP());
            MDC.put("serverName",propertiesUtil.getProperty("spring.application.name"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static String getLocalIP() {
        String hostAddress = null;
        try {
            hostAddress = InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            log.error("getLocalIP() error",e);
            hostAddress = "0.0.0.0.0.1";
        }
        return hostAddress;
    }

}
